package com.qcby.xmdemo.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.qcby.xmdemo.model.User;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class ExcelService {

    public void exportExcel(HttpServletResponse response) throws IOException {
        // 查询数据库或其他数据源获取导出的数据
        List<User> userList = getUserList();

        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=user.xlsx");

        // 导出Excel
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), User.class).build();
        WriteSheet writeSheet = EasyExcel.writerSheet("用户信息").build();
        excelWriter.write(userList, writeSheet);
        excelWriter.finish();
    }

    private List<User> getUserList() {
        // 模拟从数据库中获取用户数据
        List<User> userList = new ArrayList<>();
        userList.add(new User("张三", 25, "北京市朝阳区", "13888888888"));
        userList.add(new User("李四", 30, "上海市浦东区", "13999999999"));
        userList.add(new User("王五", 28, "广州市天河区", "13666666666"));
        return userList;
    }
}
